package com.gitee.cui.netty.echoServer;

import com.gitee.cui.util.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;

/**
 * 回显服务入站处理器
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/22 16:02
 **/
@ChannelHandler.Sharable
public class NettyEchoServerHandler extends ChannelInboundHandlerAdapter {
    public static final NettyEchoServerHandler INSTANCE = new NettyEchoServerHandler();
    private NettyEchoServerHandler() {}

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 收到数据打印出来
        ByteBuf in = (ByteBuf) msg;
        Logger.info("msg type: " + (in.hasArray() ? "堆内存" : "直接内存"));
        int length = in.readableBytes();
        byte[] array = new byte[length];
        in.getBytes(in.readerIndex(), array);
        Logger.info("server received: " + new String(array, StandardCharsets.UTF_8));

        // 将收到的数据写回客户端
        Logger.info("写回客户端前， msg.refCnt: " + ((ByteBuf) msg).refCnt());
        ChannelFuture channelFuture = ctx.writeAndFlush(msg);
        channelFuture.addListener(future -> {
           Logger.info("写回客户端后，msg.refCnt: " + ((ByteBuf) msg).refCnt());
        });
    }
}
